package JavaUtils.CSUtils;

import JavaUtils.CSUtils.Log.CLog;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author: zhouhe
 * @Date: 2019/6/19 8:48
 */
public class CFile {
    static final String tag = "CFile";

    public static void test_main(String[] args) {
        // 文件夹路径
        String path = "D:\\input.txt";
        List<String> scanListPath = ReadAllLines(path);
        assert scanListPath != null;
        for (String mytext : scanListPath) {
            //替换所有制表符
            mytext = mytext.replaceAll("\t", ",");
            System.out.println(mytext);
            //每一行都转化为新的数组，根据下标去判断参数值对应的参数是什么
            String[] strArr = mytext.split(","); //注意分隔符是需要转译
            for (int m = 0; m < strArr.length; m++) {
//                    System.out.println(strArr[m]);
                switch (m) {
                    case 0:
                        System.out.println("时间：" + strArr[m]);
                        break;
                    case 1:
                        System.out.println("甲烷：" + strArr[m]);
                        break;
                    case 2:
                        System.out.println("总烃：" + strArr[m]);
                        break;
                    case 3:
                        System.out.println("非甲烷总烃：" + strArr[m]);
                        break;
                    case 4:
                        System.out.println("氨气：" + strArr[m]);
                        break;
                    case 5:
                        System.out.println("硫化氢：" + strArr[m]);
                        break;
                    case 6:
                        System.out.println("氧气：" + strArr[m]);
                        break;
                    default:
                        break;
                }
            }
        }

    }


    public static void S_CareteDir(String dir) {
        File f = new File(dir);
        if (!f.exists()) {
            f.mkdirs(); //创建目录
        }
    }

    ///获取目录下所有匹配的文件--支持二级搜索目录
    public static List<String> getFiles(String _dir, String[] midDirArr, String[] _ignoreDirArr, String[] suffixArr, byte isTop, List<String> pathList) {
        if (pathList == null) {
            pathList = new ArrayList();
        }
        boolean topDirIsMatching = _topDirIsMatching(_dir, midDirArr, _ignoreDirArr);
        File dir = new File(_dir);
        File[] fileArr = dir.listFiles();
        assert fileArr != null;
        for (File value : fileArr) {
            String fullPath = value.getAbsolutePath();
            if (isTop == 1) {
                if (value.isFile()) {
                    _FileIsMatchingAdd(fullPath, suffixArr, pathList);
                }
            } else {
                if (value.isDirectory()) {
                    boolean isIgnore = CString.IsMatching(fullPath, _ignoreDirArr, 3);
                    if (isIgnore) {
                        continue;
                    }
                    boolean isMatching = false;
                    if (midDirArr == null || midDirArr.length == 0) {
                        getFiles(fullPath, suffixArr, isTop, pathList);
                        isMatching = true;
                    } else {
                        isMatching = CString.IsMatching(fullPath, midDirArr, 3);
                        if (isMatching) {
                            getFiles(fullPath, suffixArr, isTop, pathList);
                        }
                    }
                    if (!isMatching) {
                        //CLog.i(tag, "忽略的路径......" + fullPath);
                        getFiles(fullPath, midDirArr, _ignoreDirArr, suffixArr, isTop, pathList);
                    }
                } else if (value.isFile()) {
                    if (topDirIsMatching) {
                        _FileIsMatchingAdd(fullPath, suffixArr, pathList);
                    }
                }
            }
        }
        return pathList;
    }

    static boolean _topDirIsMatching(String fullPath, String[] midDirArr, String[] _ignoreDirArr) {
        boolean isIgnore = CString.IsMatching(fullPath, _ignoreDirArr, 3);
        if (isIgnore) {
            return false;
        }
        boolean isMatching = false;
        if (midDirArr == null || midDirArr.length == 0) {
            isMatching = true;
        } else {
            isMatching = CString.IsMatching(fullPath, midDirArr, 3);
        }
        return isMatching;
    }

    ///获取目录下所有匹配的文件
    public static List<String> getFiles(String _dir, String[] suffixArr, byte isTop) {
        return getFiles(_dir, suffixArr, isTop, null);
    }

    ///获取目录下所有匹配的文件
    public static List<String> getFiles(String _dir, String[] suffixArr, byte isTop, List<String> pathList) {
        if (pathList == null) {
            pathList = new ArrayList();
        }
        LinkedList<File> dirList = new LinkedList();
        File dir = new File(_dir);
        File[] fileArr = dir.listFiles();

        assert fileArr != null;
        for (File value : fileArr) {
            if (value.isDirectory()) {
                // 把第一层的目录，全部放入链表
                dirList.add(value);
            }
            _FileIsMatchingAdd(value.getAbsolutePath(), suffixArr, pathList);
        }
        if (isTop == 1) {
            return pathList;
        }
        // 循环遍历链表
        while (!dirList.isEmpty()) {
            // 把链表的第一个记录删除
            File tmp = dirList.removeFirst();
            // 如果删除的目录是一个路径的话
            if (tmp.isDirectory()) {
                // 列出这个目录下的文件到数组中
                fileArr = tmp.listFiles();
                if (fileArr == null) {// 空目录
                    continue;
                }
                // 遍历文件数组
                for (File value : fileArr) {
                    if (value.isDirectory()) {
                        // 如果遍历到的是目录，则将继续被加入链表
                        dirList.add(value);
                    }
                    _FileIsMatchingAdd(value.getAbsolutePath(), suffixArr, pathList);
                }
            }
        }
        return pathList;
    }

    //文件匹配添加
    static void _FileIsMatchingAdd(String filePath, String[] suffixArr, List<String> pathList) {
        if (suffixArr != null && suffixArr.length > 0) {
            if (CString.IsMatching(filePath, suffixArr, 2)) {
                pathList.add(filePath);
            }
        } else {
            pathList.add(filePath);
        }
    }

    //打印文件夹下所有的子文件夹
    public void getList_showLog(String patha) {
        String path = patha;
        File file = new File(path);
        File[] tempList = file.listFiles();
        System.out.println("该目录下对象个数：" + tempList.length);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                System.out.println("文     件：" + tempList[i]);
            }
            if (tempList[i].isDirectory()) {
                System.out.println("文件夹：" + tempList[i].getPath());
                //递归：
                getList_showLog(tempList[i].getPath());
            }
        }
    }

    //读取一个文本 一行一行读取
    public static List<String> ReadAllLines(String path) {
        List<String> list = new ArrayList<String>();
        try {
            File file = new File(path);
            if (!file.exists()) {
                CLog.ex(tag, "文件不存在..无法读取....." + path);
                return null;
            }
            // 使用一个字符串集合来存储文本中的路径 ，也可用String []数组

            FileInputStream fis = new FileInputStream(path);
            // 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8，在电脑上自己创建的txt  用GBK
            InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null) {
                // 如果 t x t文件里的路径 不包含---字符串       这里是对里面的内容进行一个筛选
                //if (line.lastIndexOf("---") < 0) {
                list.add(line);
                //}
            }
            br.close();
            isr.close();
            fis.close();
        } catch (Exception ex) {
            CLog.ex(tag, "文件不存在..无法读取....." + path, ex, true);
            return null;
        }
        return list;
    }

    public static String ReadAllTxt(String filePath) {
        StringBuffer ssb = new StringBuffer();
        try {
            FileReader reader = new FileReader(filePath);
            BufferedReader br = new BufferedReader(reader);
            String line;
            while ((line = br.readLine()) != null) {
                ssb.append(line);
            }
            br.close();
            reader.close();
        } catch (IOException e) {
            CLog.ex(tag, "错误...", e);
        }
        return ssb.toString();
    }

    public static boolean WriteAllText(String filePath, String fileData) throws IOException {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        //file.mkdirs();
        if (file.createNewFile()) {
            System.out.println("创建文件成功！");
        } else {
            System.out.println("文件已经存在不需要重复创建");
        }
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(fileData);
        }
        return true;
    }

    public static boolean WriteAllLine(String filePath, List<String> fileList) throws IOException {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        //file.mkdirs();
        if (file.createNewFile()) {
            System.out.println("创建文件成功！");
        } else {
            System.out.println("文件已经存在不需要重复创建");
        }
        try (FileWriter writer = new FileWriter(file)) {
            for (String data : fileList) {
                writer.write(data + "\n");
            }
        }
        return true;
    }

    //读取一个文本 一行一行读取
    public static List<byte[]> ReadBytesLine(String path) {
        List<byte[]> list = new ArrayList();
        try {
            File file = new File(path);
            if (!file.exists()) {
                CLog.ex(tag, "文件不存在..无法读取....." + path);
                return null;
            }
            // 使用一个字符串集合来存储文本中的路径 ，也可用String []数组
            FileInputStream fis = new FileInputStream(path);
            // 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8，在电脑上自己创建的txt  用GBK
            //InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            //BufferedReader br = new BufferedReader(isr);
            byte[] bytes = new byte[1024 * 1024];
            int len = 0;
            while ((len = fis.read(bytes)) > 0) {
                if (len == bytes.length) {
                    list.add(bytes);
                } else {
                    list.add(CBytes.subBytes(bytes, 0, len));
                    break;
                }
            }
            //br.close();
            //isr.close();
            fis.close();
        } catch (Exception ex) {
            CLog.ex(tag, "文件不存在..无法读取....." + path, ex, true);
            return null;
        }
        return list;
    }

    public static byte[] ReadAllBytes(String path) {
        List<byte[]> list = ReadBytesLine(path);
        int len = 0;
        for (byte[] bb : list) {
            len += bb.length;
        }
        byte[] newBytes = new byte[len];
        len = 0;
        for (byte[] bb : list) {
            System.arraycopy(bb, 0, newBytes, len, bb.length);
            len += bb.length;
        }
        return newBytes;
    }

    //拷贝文件
    public static void fileCopy(String sourcePath, String targetPath) {
        CLog.f("S_fileCopy.....%s........%s", sourcePath, targetPath);
        int n = 0;
        try {
            FileInputStream source = new FileInputStream(sourcePath);
            FileOutputStream target = new FileOutputStream(targetPath);
            while ((n = source.read()) != -1) {
                target.write(n);
            }
            source.close();
            target.close();
        } catch (FileNotFoundException e) {
            CLog.ex(tag, "S_fileCopy.1.错误...", e);
        } catch (IOException e) {
            CLog.ex(tag, "S_fileCopy.2.错误...", e);
        }
    }

    /**
     * 删除空目录
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    public static boolean S_delete(String dir) {
        CLog.f("删除路径......%s", dir);
        boolean bb = S_delete(new File(dir));
        CLog.f("删除路径..完成....%s", dir);
        if (bb) {
            CLog.f("删除失败...........%s", dir);
        }
        return bb;
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     */
    public static boolean S_delete(File dir) {
        if (!dir.exists()) {
            CLog.f("目录不存在.......%s", dir.getPath());
            return false;
        }
        if (dir.isFile()) {
            CLog.f("删除文件........%s", dir.getPath());
            return dir.delete();
        } else if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            assert children != null;
            for (String child : children) {
                String path = dir.getPath() + "\\" + child;
                boolean success = S_delete(new File(path));
                if (!success) {
                    CLog.f("删除失败.......%s", path);
                    // return false;
                }
            }
        }
        //目录此时为空，可以删除
        return dir.delete();
    }

    //保存文件
    public static void S_Save(String savePath, String data) {
        S_Save(savePath, CBytes.stringToBytes(data));
    }

    //保存文件
    public static void S_Save(String savePath, byte[] data) {
        try {
            FileOutputStream target = new FileOutputStream(savePath);
            target.write(data);
            target.close();
        } catch (FileNotFoundException e) {
            CLog.ex(tag, "S_Save.1.错误.", e);
        } catch (IOException e) {
            CLog.ex(tag, "S_Save.2.错误.", e);
        }
    }


    public static boolean S_copyDir(String oldPath, String newPath) {
        CLog.f("拷贝目录.....%s........%s", oldPath, newPath);
        boolean result = true;
        String[] filePaths = new File(oldPath).list();

        if (filePaths != null && filePaths.length > 0) {
            if (!new File(newPath).exists()) {
                if (!new File(newPath).mkdirs()) {
                    CLog.ex(tag, "文件夹创建失败");
                    return false;
                }
            }
            try {
                for (String filePath : filePaths) {
                    if (new File(oldPath + File.separator + filePath).isDirectory()) {
                        S_copyDir(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                    } else if (new File(oldPath + File.separator + filePath).isFile()) {
                        //复制文件到另一个目录
                        S_copyFile(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                        //移动文件至另一个目录
//                        String path0 = oldPath + File.separator + filePath;
//                        String path1 = newPath + File.separator + filePath;
//                        if (!new File(path0).renameTo(new File(path1))) {
//                            System.out.println(oldPath + File.separator + filePath + "文件复制失败");
//                            result = false;
//                            //break;
//                        }
                    }
                }
            } catch (Exception e) {
                CLog.ex(tag, "错误...", e);
            }
        }
        return result;
    }

    public static void S_copyFile(String oldPath, String newPath) throws IOException {
        CLog.f("拷贝文件.....%s........%s", oldPath, newPath);
        File oldFile = new File(oldPath);
        if (!oldFile.exists()) {
            CLog.ef("拷贝文件.失败......文件不存在......%s....", oldPath);
            return;
        }
        try {
            File file = new File(newPath);
            FileInputStream in = new FileInputStream(oldFile);
            try {
                FileOutputStream out = new FileOutputStream(file);
                byte[] buffer = new byte[2097152];
                int len = 10;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
                in.close();
                out.close();
            } catch (Exception ex) {
                in.close();
                CLog.ex(tag, "拷贝文件.失败....文件错误..", ex, true);
            }
        } catch (Exception ex) {
            CLog.ex(tag, "拷贝文件.失败222....文件错误..", ex, true);
        }
    }

    /**
     * 拷贝文件夹并-替换文本文件中的字符串
     *
     * @param oldPath
     * @throws IOException
     */
    public static boolean S_moveDir_ReplacTextContent(String oldPath, String newPath, String srcStr0, String replaceStr0) {
        boolean result = true;
        String[] filePaths = new File(oldPath).list();

        if (filePaths != null && filePaths.length > 0) {
            if (!new File(newPath).exists()) {
                if (!new File(newPath).mkdirs()) {
                    System.out.println("文件夹创建失败");
                    return false;
                }
            }

            try {
                for (String filePath : filePaths) {
                    if (new File(oldPath + File.separator + filePath).isDirectory()) {
                        S_moveDir_ReplacTextContent(oldPath + File.separator + filePath, newPath + File.separator + filePath, srcStr0, replaceStr0);
                    } else if (new File(oldPath + File.separator + filePath).isFile()) {
                        //复制文件到另一个目录
                        S_copyFile_ReplacTextContent(oldPath + File.separator + filePath, newPath + File.separator + filePath, srcStr0, replaceStr0);
                        //移动文件至另一个目录
//                        if(!new File(oldPath + File.separator + filePath).renameTo(new File(newPath + File.separator + filePath))){
//                            System.out.println(oldPath + File.separator + filePath +"文件复制失败");
//                            result = false;
//                            break;
//                        }
                    }
                }
            } catch (Exception e) {
                CLog.ex(tag, "错误...", e);
            }
        }

        return result;
    }

    /**
     * 拷贝并-替换文本文件中的字符串
     *
     * @param oldPath
     * @throws IOException
     */
    public static void S_copyFile_ReplacTextContent(String oldPath, String targetPath, String srcStr0, String replaceStr0) throws IOException {
        // 读
        //File file = new File(path);
        //FileReader in = new FileReader(file);
        BufferedReader bufIn = new BufferedReader(new FileReader(new File(oldPath)));
        // 内存流, 作为临时流
        CharArrayWriter tempStream = new CharArrayWriter();
        // 替换
        String line = null;
        while ((line = bufIn.readLine()) != null) {
            if (srcStr0 != null) {
                // 替换每行中, 符合条件的字符串
                line = line.replaceAll(srcStr0, replaceStr0);
            }
            // 将该行写入内存
            tempStream.write(line);
            // 添加换行符
            tempStream.append(System.getProperty("line.separator"));
        }
        // 关闭 输入流
        bufIn.close();
        // 将内存中的流 写入 文件
        FileWriter out = new FileWriter(new File(targetPath));
        tempStream.writeTo(out);
        out.close();
        System.out.println("====path:" + oldPath);
    }


    public static List<String> DfStrToFileList(String dfStr) {
        List<String> dirList = new ArrayList<>();
        List<String> fileList = new ArrayList<>();
        String[] dataArr = dfStr.split("\n");

        int currIndex = 0;
        String currDirName = "";
        String splitDir = CString.cSplit07 + "";
        for (String path : dataArr) {
            int index = path.indexOf(CString.cSplit07);
            if (index >= 0) {
                String[] sss = path.split(splitDir);
                currIndex = Integer.parseInt(sss[0]);
                currDirName = sss[1];
                if (dirList.size() > currIndex) {
                    dirList.set(currIndex, currDirName);
                } else {
                    dirList.add(currIndex, currDirName);
                }
            } else {
                String dirPath = "";
                for (int i = 0; i < currIndex + 1; i++) {
                    dirPath += dirList.get(i) + "/";
                }
                dirPath += path;
                fileList.add(dirPath);
            }
        }

        return fileList;
    }

    //移除文件列表的头部
    public static void RemoveFileListHead(String dir, List<String> fileList) {
        dir = dir.replace('\\', '/');
        if (!dir.endsWith("/")) {
            dir += "/";
        }
        int len = dir.length();
        for (int i = 0, count = fileList.size(); i < count; i++) {
            String filePath = fileList.get(i);
            String _filePath = filePath.substring(len).replace('\\', '/');
            fileList.set(i, _filePath);
        }
    }

    public static String FileListToDfStr(List<String> fileList) {
        DirFile lastDirFile = new DirFile("");
        for (String filePath : fileList) {
            String[] dirNameArr = filePath.replace('\\', '/').split("/");
            lastDirFile.AddSub(dirNameArr, 0);
        }
        StringBuilder ssb = new StringBuilder();
        lastDirFile.WriteString(-1, ssb);
        return ssb.toString();
    }

    static class DirFile {
        public DirFile parentDir;
        public String dirName;
        public Map<String, DirFile> dirFileDic;

        public DirFile(String dirName) {
            this.dirName = dirName;
        }

        public void AddSub(String[] dirNameArr, int index) {
            if (index >= dirNameArr.length) {
                return;
            }
            if (dirFileDic == null) {
                dirFileDic = new HashMap<>();
            }
            String dirName = dirNameArr[index];
            ++index;
            DirFile subDirFile;
            if (dirFileDic.containsKey(dirName)) {
                subDirFile = dirFileDic.get(dirName);
            } else {
                subDirFile = new DirFile(dirName);
                subDirFile.parentDir = this;
                dirFileDic.put(dirName, subDirFile);
            }
            subDirFile.AddSub(dirNameArr, index);
        }

        public void WriteString(int dirLayer, StringBuilder ssb) {
            if (dirFileDic != null && dirFileDic.size() > 0) {
                if (dirLayer < 0) {//这是根的空目录
                    dirLayer = 0;
                } else {
                    ssb.append(dirLayer + (CString.cSplit07 + dirName + "\n"));
                    dirLayer++;
                }
                for (Map.Entry<String, DirFile> entry : dirFileDic.entrySet()) {
                    entry.getValue().WriteString(dirLayer, ssb);
                }
            } else {
                ssb.append(dirName + "\n");
            }
        }
    }
}



